defmodule ChoicePlayground.PageView do
  use ChoicePlayground.Web, :view
  alias ChoicePlayground.Repo

  def render("index.json", %{question: question}) do
    render_question(question)
    # %{data: render_many(pages, ChoicePlayground.PageView, "page.json")}
  end

  def render("analysis.json", %{result: result}) do
    result
  end

  def render("answer.json", %{result: result}) do
    result
  end

  def render("page.json", %{page: page}) do
    %{title: page.title}
  end

  defp render_question(question) do
    case question do
      nil -> "没有相关问卷"
      _ -> %{
        id: question.seq,
        title: question.title,
        question: Enum.map(question.question, fn (q) ->
          result = q |> Repo.preload(:question_content)
          case result.type do
            "fill" -> %{
              id: result.seq,
              type: result.type,
              title: result.title,
              required: result.required,
            }
            "select" -> %{
              id: result.seq,
              type: result.type,
              title: result.title,
              required: result.required,
              options: Enum.map(result.question_content, fn(content) ->
                  %{
                    id: content.seq,
                    content: content.content,
                  }
                end)
            }
          end
        end)
      }
    end
  end
end
